package nbcp.web.open

import ch.qos.logback.classic.Logger
import io.swagger.annotations.*
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import nbcp.base.extend.*
import org.springframework.web.bind.annotation.*
import nbcp.base.comm.*
import nbcp.base.config.ActionDocBeanGather
import nbcp.comm.JsonpMapping
import nbcp.db.IdName
import nbcp.db.doLogin
import nbcp.db.mongo.*
import nbcp.db.mongo.entity.AdminUser
import nbcp.db.mongo.entity.SysUser
import nbcp.web.LoginUser
import java.io.File
import java.lang.reflect.ParameterizedType
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession

/**
 * Created by udi on 17-3-19.
 */
@RestController
@JsonpMapping("/")
@OpenAction
class Open_Controller {
    companion object {
        private val logger = LoggerFactory.getLogger(this::class.java.declaringClass)
    }

    //    private fun print_it(doc: ActionDocBeanGather.ActionDoc) {
//        println(doc.remark + " " + doc.methods.joinToString(",") + " actions:")
//
//        doc.actions.forEachIndexed { index, act ->
//            var routings = mutableListOf<String>()
//            act.routings.forEach {
//                if (doc.routings.any()) {
//                    doc.routings.forEach { d ->
//                        routings.add(d + it)
//                    }
//                } else {
//                    routings.add(it)
//                }
//            }
//            println("\t" + index.toString() + ":" + act.remark + " " + act.methods.joinToString(",") + " url: " + routings.joinToString(","))
//            println("\t参数: " + act.parameters.map { it.name + ":" + it.type.simpleName }.joinToString(","))
//
//            if (act.returnType is ParameterizedType) {
//                println("\t结果: " + (act.returnType as ParameterizedType).rawType.typeName + ": " + (act.returnType as ParameterizedType).actualTypeArguments.map { it.typeName }.joinToString(","))
//            } else {
//                println("\t结果: " + act.returnType.typeName)
//            }
////            println("\t\t: " + act.returnType. .map { it.name + it.type.simpleName }.joinToString(","))
//        }
//        println()
//    }
    @GetMapping("/doc")
    fun test(path: String): ApiResult<Any> {
        var data = ActionDocBeanGather.map
                .filter { it.value.routings.startsWith(path) }


        if (data.size == 0) {
            return ApiResult()
        } else if (data.size == 1) {
            return ApiResult.of(data.values.first())
        }

        return ApiResult.of(data.map { it.value.routings })
    }

    @ApiOperation(value = "退出登录")
    @JsonpMapping("/logout")
    fun logout(session: HttpSession, request: HttpServletRequest): JsonResult {

        session.invalidate();
//        var openId = request.getHeader("wxoid");
//        rer.sys.jwdSession.delete(openId.AsString(request.requestedSessionId))

        return JsonResult()
    }

    @ApiOperation(value = "登录")
    @JsonpMapping("/login")
    fun login(loginName: String,
              password: String,
              validateCode: String?,
              request: HttpServletRequest,
              session: HttpSession): ApiResult<AdminUser> {


        var validateCode = validateCode ?: ""
        var app = request.getHeader("app") ?: "pc";

        if (app == "wx") {

        } else {
            if (validateCode.length != 4) {
                return ApiResult("验证码错误，请重试！")
            }
            if (validateCode.toLowerCase().toCharArray().intersect(session.ValidateCode.toCharArray().toList()).size < 3) {
                return ApiResult("验证码错误，请重试！")
            }
        }

        return mor.admin.adminUser.doLogin(loginName, password, request);
    }

//    data class cn_cityModel(var c: Int, var n: String)

//    @PostMapping("/getChildCitys")
//    fun getChildCitys(code: Int, response: HttpServletResponse): JsonResult? {
//        var ret = JsonResult()
//        if (code == 0) {
//            return JsonResult("城市code不能为空")
//        }
//        if (code % 100 != 0) return ret;
//
//        var value = rer.sys.sysCityJson.get(code.toString());
//        if (value.HasValue) {
//            response.WriteJsonRawValue(value);
//            return null;
//        }
//
//
//        value = ApiResult(
//                data = mor.system.sysCity.query()
//                        .where(mor.system.sysCity.pcode match code)
//                        .toList(CodeName::class.java)
//                        .map { cn_cityModel(it.code, it.name) }
//        )
//                .ToJson();
//
//
//        rer.sys.sysCityJson.set(code.toString(), value);
//
//        response.WriteJsonRawValue(value);
//        return null;
//    }

    @Value("\${spring.application.name}")
    var applicationName: String = "";

    @GetMapping("/log")
    fun log(filter: List<String>?, not: List<String>?, tail: Boolean?,
            extCount: Int = 0, matchLines: Int, help: Boolean?,
            f:List<String>?,c:Int=0,n:Int=0,
            request: HttpServletRequest): String {

        var logFile = (logger as Logger).getLoggerFile("FILE-OUT");


        var log_text = File(logFile).FilterLines(
                n.AsInt( matchLines),
                c.AsInt(extCount),
                f?:filter ?: emptyList(),
                not ?: emptyList(),
                tail
                        ?: true).joinToString("\n")

        var help_html = "";
        if( help == true){
            help_html = """<pre>
    日志参数,优先使用简写参数：
        filter:f  表示过滤匹配条件，可以多个
        not:      表示过滤匹配不满足条件的行，可以多个
        tail:     表示是否从最底部显示，默认是 true
        extCount:c 表示如果有 filter , not 的话，返回匹配行的前后多少行。
        matchLines:n 表示返回的总行数
</pre>
<hr />"""
        }

        return """<!DOCTYPE html>
<html>
<head><title>${applicationName} - 日志</title></head>
<body>${help_html}<pre>${log_text}</pre></body>
</html>
"""
    }

}